﻿
$c.fn.datepicker = function (config) {
    var obj = function (selector, config) {
        this.selector = selector;
        this.config = $.extendEx({}, this.defConfig, config);
        var date = new Date();
        if ($.trim(this.selector.val())) {
            date = new Date($.trim(this.selector.val()));
        }
        this.config.date = date;
        this.date = new Date(date);//不同直接=date,因为这样引用的是同一个对象.
        //alert(this.date);
        //$(this.selector).addClass('kui-datepicker');
    }
    obj.prototype.defConfig = {
        format: 'yyyy-MM-dd',
        type: 'date'
        //width:240
    };
    
    obj.prototype.datepicker = function () {
        var _obj = this;
        this.selector.click(function () {
            
            //var year = date.getFullYear();             //获取日期中的年份
            //var month = date.getMonth();              //获取日期中的月份(需要注意的是：月份是从0开始计算，获取的值比正常月份的值少1)
            //var day = date.getDate();
            //_obj.initDate = date;
            //alert(_obj.date);
            _obj.show();
            _obj.setPosition();
            $(window).scroll(function () {
                if (_obj.table.is(':visible')){
                    _obj.setPosition();
                }
            });
        });
    }
    obj.prototype.setPosition = function () {
        var _obj = this;
        var border_bottom_width = parseFloat(this.selector.css('border-bottom-width').split('px')[0]);
        var left = this.selector.offset().left;
        var top = this.selector.offset().top + this.selector.height() + border_bottom_width;
        _obj.table.css('left', left - $(document).scrollLeft());
        _obj.table.css('top', top - $(document).scrollTop());
    }
    obj.prototype.show = function () {
        var _obj = this;
        //if (month == 2 && !_obj.isLeap(obj.date.getFullYear()) && month == 29) {
        //    month = 28;
        //}
        //var border_bottom_width = parseFloat(this.selector.css('border-bottom-width').split('px')[0]);
        //var left = this.selector.offset().left;
        //var top = this.selector.offset().top + this.selector.height() + border_bottom_width;
        //var width = this.selector.width();
        var table = $('<div class="kui-date" style="position:fixed;margin:0;"></div>').appendTo($("body"));
        _obj.table = table;

        var rowHeader = $('<div class="kui-date-tr kui-date-head"><div class="kui-date-td kui-date-pre-year"><div class="kui-date-angle-left"></div></div><div class="kui-date-td kui-date-year-text"></div><div class="kui-date-td kui-date-year-selector"><div class="kui-date-angle-down"></div></div><div class="kui-date-td kui-date-next-year"><div class="kui-date-angle-right"></div></div><div class="kui-date-td kui-date-pre-month"><div class="kui-date-angle-left"></div></div><div class="kui-date-td kui-date-month-text"></div><div class="kui-date-td kui-date-month-selector"><div class="kui-date-angle-down"></div></div><div class="kui-date-td kui-date-next-month"><div class="kui-date-angle-right"></div></div><div class="clear"></div></div>');
        table.append(rowHeader);

        rowHeader.find('.kui-date-pre-year').click(function () {
            //table.remove();
            //_obj.draw(year - 1, month,day);
            _obj.date.setFullYear(_ob.date.getFullYear() - 1);
            _obj.reDraw();

        });
        rowHeader.find('.kui-date-next-year').click(function () {
            _obj.date.setFullYear(_ob.date.getFullYear() + 1);
            _obj.reDraw();
        });

        rowHeader.find('.kui-date-pre-month').click(function () {
            var month = _obj.date.getMonth();
            var day = _obj.date.getDate();
            if (month == 0) {
                _obj.date.setFullYear(_obj.date.getFullYear() - 1, 11, _obj.date.getDate());
            }
            else {
                var __date = new Date(_obj.date.getFullYear(),month-1,_obj.date.getDate());
                if (__date.getDate() == day) {
                    _obj.date.setFullYear(_obj.date.getFullYear(), month-1, day);
                }
                else {
                    _obj.date.setFullYear(_obj.date.getFullYear(), month - 1, 1);//比如:5月31，上月没有4月31则直接设为4月1日即可.
                }
            }
            _obj.reDraw();
        });
        rowHeader.find('.kui-date-next-month').click(function () {
            table.remove();
            if (month == 12) {
                _obj.draw(year + 1, 1,day);
            }
            else {
                _obj.draw(year, month + 1,day);
            }

            var month = _obj.date.getMonth();
            var day = _obj.date.getDate();
            if (month == 11) {
                _obj.date.setFullYear(_obj.date.getFullYear() + 1, 0, _obj.date.getDate());
            }
            else {
                var __date = new Date(_obj.date.getFullYear(), month + 1, _obj.date.getDate());
                if (__date.getDate() == day) {
                    _obj.date.setFullYear(_obj.date.getFullYear(), month + 1, day);
                }
                else {
                    _obj.date.setFullYear(_obj.date.getFullYear(), month + 1, 1);//比如:5月31，下月没有6月31则直接设为6月1日即可.
                }
            }
            _obj.reDraw();

        });
        var rowWeekday = $('<div class="kui-date-tr kui-date-weekday"><div class="kui-date-td"><span>日</span></div><div class="kui-date-td"><span>一</span></div><div class="kui-date-td"><span>二</span></div><div class="kui-date-td"><span>三</span></div><div class="kui-date-td"><span>四</span></div><div class="kui-date-td"><span>五</span></div><div class="kui-date-td"><span>六</span></div><div class="clear"></div></div>');
        table.append(rowWeekday);

        var datesPanel = $('<div class="kui-date-datespanel"></div>').appendTo(table);

        var rowBtns = $('<div class="kui-date-tr kui-date-btns"><div class="kui-date-td kui-date-time-lable" style="display:none;">时间</div><div class="kui-date-td kui-date-time" style="display:none;"><input readonly="readonly" class="kui-date-time-hh" value="00"/>:<input readonly="readonly" class="kui-date-time-mm" value="00"/>:<input readonly="readonly" class="kui-date-time-ss" value="00"/></div><div class="kui-date-td kui-date-btn-clear"><a style="display:block;">清空</a></div><div class="kui-date-td kui-date-btn-ok"><a style="display:block;">确定</a></div><div class="kui-date-td kui-date-btn-today"><a style="display:block;">今天</a></div><div class="clear"></div></div>');
        table.append(rowBtns);
        if (_obj.config.type == 'datetime') {
            rowBtns.find('.kui-date-time-lable,.kui-date-time').show();
        }
        if (_obj.config.type == 'date') {
            rowBtns.find('.kui-date-btn-clear').addClass('kui-date-btn-first');
        }

        rowBtns.find('.kui-date-btn-clear').click(function () {
            _obj.selector.val('');
            table.remove();
        });
        rowBtns.find('.kui-date-btn-today').click(function () {
            _obj.selector.val($c.date.format(new Date(),_obj.config.format));
            table.remove();
        });
        rowBtns.find('.kui-date-btn-ok').click(function () {
            _obj.selector.val($c.date.format(_obj.date, _obj.config.format));
            table.remove();
        });

        table.find('.kui-date-year-selector,.kui-date-year-text').click(function () {
            table.find('.kui-date-month-panel,.kui-date-hour-panel,.kui-date-minute-panel,.kui-date-second-panel').remove();
            _obj.showYearPanel(_obj.date.getFullYear());
        });
        table.find('.kui-date-month-selector,.kui-date-month-text').click(function () {
            table.find('.kui-date-year-panel,.kui-date-hour-panel,.kui-date-minute-panel,.kui-date-second-panel').remove();
            _obj.showMonthPanel();
        });
        table.find('.kui-date-time-hh').click(function () {
            table.find('.kui-date-year-panel,.kui-date-month-panel,.kui-date-minute-panel,.kui-date-second-panel').remove();
            _obj.showHourPanel();
        });
        table.find('.kui-date-time-mm').click(function () {
            table.find('.kui-date-year-panel,.kui-date-month-panel,.kui-date-hour-panel,.kui-date-second-panel').remove();
            _obj.showMinutePanel();
        });
        table.find('.kui-date-time-ss').click(function () {
            table.find('.kui-date-year-panel,.kui-date-month-panel,.kui-date-hour-panel,.kui-date-minute-panel').remove();
            _obj.showSecondPanel();
        });
        _obj.reDraw();
    }

    obj.prototype.reDraw = function () {
        var _obj = this;
        var table = _obj.table;
        var year = _obj.date.getFullYear();
        var month = _obj.date.getMonth();//注:0~11,月份是从0开始计算，获取的值比正常月份的值少1.
        //month = month + 1;
        var day = _obj.date.getDate();
        var hh = _obj.date.getHours();//0~23
        var mm = _obj.date.getMinutes();//0 ~ 59
        var ss = _obj.date.getSeconds();//0 ~ 59

        table.find('.kui-date-year-text').html('<span>' + year + '年</span>');
        table.find('.kui-date-month-text').html('<span>' + (month + 1) + '月</span>');

        var datesPanel = table.find('.kui-date-datespanel');
        datesPanel.html('');

        var firstDay = new Date(year, month, 1);//获取当月第一天,注:月份是从0开始的.
        var dayOfWeek = firstDay.getDay();//判断第一天是星期几(返回[0-6]中的一个，0代表星期天，1代表星期一，以此类推)
        var days_per_month = new Array(31, 28 + _obj.isLeap(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);//创建月份数组,记录每个月有多少天.
        var rowNum = Math.ceil((dayOfWeek + days_per_month[month]) / 7);//确定日期表格所需的行数 //Math.ceil向上取整.是星期几,第一行前面就有几个日期是上一个月的.

        for (var i = 0; i < rowNum; i++) {         //二维数组创建日期表格
            var tr = $('<div class="kui-date-tr kui-date-number"></div>').appendTo(datesPanel);
            if (i == rowNum - 1) {
                tr.addClass('kui-date-row-last');
            }
            if (i == 0) {
                tr.addClass('kui-date-row-first');
            }
            for (var j = 0; j < 7; j++) {
                var idx = 7 * i + j;                //为每个表格创建索引,从0开始
                var date = idx - dayOfWeek + 1;          //将当月的1号与星期进行匹配
                var td = $('<div class="kui-date-td kui-date-col-' + (j + 1) + '"><span></span></div>').appendTo(tr);
                if (date <= 0) {//第一行前几个日期是上个月的.
                    var day_pre_month = 31;//去年12月
                    if (month > 0) {
                        day_pre_month = days_per_month[month - 1];
                    }
                    date = day_pre_month + date;
                    td.addClass('kui-date-nothis');
                    var _date = new Date(_obj.date);
                    _date.setFullYear(year, month - 1, date);
                    if (month == 0) {
                        _date.setFullYear(year - 1, 11, date);//去年12月份
                    }
                    td[0].date = _date;
                }
                else if (date > days_per_month[month]) {//最后一行后几个日期是下个月的.
                    var day_next_month = 31;//明年1月
                    if (month < 11) {
                        day_next_month = days_per_month[month + 1];
                    }
                    date = date - days_per_month[month];
                    td.addClass('kui-date-nothis');
                    var _date = new Date(_obj.date);
                    _date.setFullYear(year, month + 1, date)
                    if (month == 11) {
                        _date.setFullYear(year + 1, 0, date);//明年1月
                    }
                    td[0].date = _date;
                }
                else {
                    var _date = new Date(_obj.date);
                    _date.setFullYear(year, month, date);//当前月
                    td[0].date = _date;
                    if (day == date) {//年月不管.
                        $(td).addClass('kui-date-today');//高亮显示当天.
                    }
                }
                td.find('span').html(date);

                td.click(function () {
                    _obj.selector.val($c.date.format(this.date, _obj.config.format));
                    table.remove();
                });
            }
            $(tr).append('<div class="clear"></div>')
        }//for 结束

        table.find('.kui-date-time-hh').val('' + (hh < 10 ? '0' : '') + '' + hh + '');
        table.find('.kui-date-time-mm').val('' + (mm < 10 ? '0' : '') + '' + mm + '');
        table.find('.kui-date-time-ss').val('' + (ss < 10 ? '0' : '') + '' + ss + '');
    }

    obj.prototype.showYearPanel = function (year) {
        var _obj = this;
        var panel = $('<div class="kui-date-year-panel" style="position:absolute;"><div class="kui-date-year-panel-head"><div class="kui-date-angle-up"></div></div><div class="kui-date-year-panel-body"></div><div class="kui-date-year-panel-foot"><div class="kui-date-angle-down"></div></div></div>').appendTo(_obj.table);
        
        _obj.reDrawYearPanel(year);

        panel.css('left', _obj.table.find('.kui-date-head').position().left);
        panel.css('top', _obj.table.find('.kui-date-weekday').position().top - 5);

        panel.find('.kui-date-year-panel-head').click(function () {
            //panel.remove();
            //_obj.showYearPanel(year - 14, month, day);
            _obj.reDrawYearPanel(year - 14);
        });
        panel.find('.kui-date-year-panel-foot').click(function () {
            //panel.remove();
            //_obj.showYearPanel(year + 14, month, day);
            _obj.reDrawYearPanel(year + 14);
        });
    }
    obj.prototype.reDrawYearPanel = function (year) {
        var _obj=this;
        var table=_obj.table;
        var panel = table.find('.kui-date-year-panel');
        var year_panel_body = panel.find('.kui-date-year-panel-body');
        for (var i = 0; i < 14; i++) {
            var year_item = $('<div class="kui-date-year-item" style="float:left;">' + (year - 7 + i) + '年</div>').appendTo(year_panel_body);
            year_item.attr('year', year - 7 + i);
            if (i % 2 == 1) {
                year_item.addClass('kui-date-year-right-col');
                year_panel_body.append('<div class="clear"></div>')
            }
            if (year - 7 + i == year) {
                year_item.addClass('kui-date-year-item-current');
            }
            year_item.click(function () {
                _obj.date.setFullYear(parseInt($(this).attr('year'), 10));
                panel.remove();
                _obj.reDraw();
            });
        }
    }

    obj.prototype.showMonthPanel = function () {
        var _obj = this;
        var panel = $('<div class="kui-date-month-panel" style="position:absolute;"></div>').appendTo(_obj.table);
        for (var i = 0; i < 12; i++) {
            var month_item = $('<div class="kui-date-month-item" style="float:left;">'+(i<9?"0":"")+'' + (i + 1) + '&nbsp;月</div>').appendTo(panel);
            month_item.attr('month', i);
            if (i % 2 == 1) {
                month_item.addClass('kui-date-month-right-col');
                panel.append('<div class="clear"></div>')
            }
            if (i== _obj.date.getMonth()) {
                month_item.addClass('kui-date-month-item-current');
            }
            month_item.click(function () {
                _obj.date.setMonth(parseInt($(this).attr('month'), 10));
                panel.remove();
                _obj.reDraw();
            });
        }
        panel.css('left', _obj.table.find('.kui-date-pre-month').position().left + parseInt(_obj.table.find('.kui-date-pre-month').css('margin-left').split('px')[0], 10));
        panel.css('top', _obj.table.find('.kui-date-weekday').position().top - 5);
    }

    obj.prototype.showHourPanel = function () {
        var _obj = this;
        var hh = _obj.date.getHours();
        var panel = $('<div class="kui-date-hour-panel" style="position:absolute;"><div class="kui-date-hour-panel-head"><div class="kui-date-angle-up"></div></div><div class="kui-date-hour-panel-body"></div></div>').appendTo(_obj.table);
        var panel_body = panel.find('.kui-date-hour-panel-body');
        for (var i = 0; i < 24; i++) {
            var hour_item = $('<div class="kui-date-hour-item" style="float:left;">' + i + '</div>').appendTo(panel_body);
            hour_item.attr('hour', i);
            if (i % 5 == 4) {
                panel_body.append('<div class="clear"></div>')
            }
            if (hh == i) {
                hour_item.addClass('kui-date-hour-item-current');
            }
            hour_item.click(function () {
                _obj.date.setHours(parseInt($(this).attr('hour'), 10));
                panel.remove();
                _obj.reDraw();
            });
        }
        panel.css('left', _obj.table.find('.kui-date-time-lable').position().left);
        panel.css('top', _obj.table.find('.kui-date-time-lable').position().top - panel.height());
    }
    
    obj.prototype.showMinutePanel = function () {
        var _obj = this;
        var mm = _obj.date.getMinutes();
        var panel = $('<div class="kui-date-minute-panel" style="position:absolute;"><div class="kui-date-minute-panel-head"><div class="kui-date-angle-up"></div></div><div class="kui-date-minute-panel-body"></div></div>').appendTo(_obj.table);
        var panel_body = panel.find('.kui-date-minute-panel-body');
        for (var i = 0; i < 60; i++) {
            var hour_item = $('<div class="kui-date-minute-item" style="float:left;">' + i + '</div>').appendTo(panel_body);
            hour_item.attr('minute', i);
            if (i % 10 == 9) {
                panel_body.append('<div class="clear"></div>')
            }
            if (mm == i) {
                hour_item.addClass('kui-date-minute-item-current');
            }
            hour_item.click(function () {
                _obj.date.setMinutes(parseInt($(this).attr('minute'), 10));
                panel.remove();
                _obj.reDraw();
            });
        }
        panel.css('left', _obj.table.find('.kui-date-time-lable').position().left);
        panel.css('top', _obj.table.find('.kui-date-time-lable').position().top - panel.height());
    }

    obj.prototype.showSecondPanel = function () {
        var _obj = this;
        var ss = _obj.date.getSeconds();
        var panel = $('<div class="kui-date-second-panel" style="position:absolute;"><div class="kui-date-second-panel-head"><div class="kui-date-angle-up"></div></div><div class="kui-date-second-panel-body"></div></div>').appendTo(_obj.table);
        var panel_body = panel.find('.kui-date-second-panel-body');
        for (var i = 0; i < 60; i++) {
            var second_item = $('<div class="kui-date-second-item" style="float:left;">' + i + '</div>').appendTo(panel_body);
            second_item.attr('second', i);
            if (i % 10 == 9) {
                panel_body.append('<div class="clear"></div>')
            }
            if (ss == i) {
                second_item.addClass('kui-date-second-item-current');
            }
            second_item.click(function () {
                _obj.date.setSeconds(parseInt($(this).attr('second'), 10));
                panel.remove();
                _obj.reDraw();
            });
        }
        panel.css('left', _obj.table.find('.kui-date-time-lable').position().left);
        panel.css('top', _obj.table.find('.kui-date-time-lable').position().top - panel.height());
    }

    //判断闰年
    obj.prototype.isLeap = function (year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    };
    var selector = this.jo;
    var _obj = new obj(selector, config || {});
    _obj.datepicker();

    //return _obj;
};